package com.aaa.tars.service.impl;

import com.aaa.tars.dao.ScenicAuditDao;
import com.aaa.tars.dao.ScenicDao;
import com.aaa.tars.entity.Scenic;
import com.aaa.tars.entity.ScenicAudit;
import com.aaa.tars.service.ScenicService;
import com.aaa.tars.util.CustomException;
import com.aaa.tars.util.Page;
import com.aaa.tars.util.Result;
import com.aaa.tars.util.ResultUtil;
import com.aaa.tars.util.ResultStatus;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.*;

/**
 * @FileName: SceniceServicImpl
 * @Description:
 * @Author: 李宗盛
 * @CreateTime: 2025/9/8 15:54
 * @Version: 17
 */
@Service
public class ScenicServiceImpl implements ScenicService {
    @Resource
    private ScenicDao scenicDao;

    @Resource
    private ScenicAuditDao scenicAuditDao;
    @Override
    public Scenic queryScenicWithTickets(Integer scenicId) {
        if (scenicId == null || scenicId <= 0) {
            throw new CustomException(ResultStatus.ERROR.getStatusCode(), "景区ID非法");
        }
        // 复用queryById，因Mapper的ScenicWithTicketsMap已配置关联查询
        return scenicDao.queryById(scenicId);
    }

    @Override
    public Scenic queryScenicWithDots(Integer scenicId) {
        if(scenicId ==null || scenicId<=0){
            throw  new CustomException(ResultStatus.ERROR.getStatusCode(), "景区Id非法");
        }
        return  scenicDao.queryScenicWithDots(scenicId);
    }

    @Override
    public Scenic queryScenicWithTicketsAndDots(Integer scenicId) {
        if(scenicId ==null || scenicId<=0){
            throw  new CustomException(ResultStatus.ERROR.getStatusCode(),ResultStatus.ERROR.getStatusMessage());
        }
        return  scenicDao.queryScenicWithTicketsAndDots(scenicId);
    }

    @Override
    public Scenic queryById(Integer scenicId) {
        return this.scenicDao.queryById(scenicId);
    }

    @Override
    public List<Scenic> queryAll() {
        return scenicDao.queryAll(null);
    }

    @Override
    public List<Scenic> frontQueryAll() {
        return scenicDao.frontQueryAll(null);
    }

    @Override
    public PageInfo queryByPage(Page<Scenic> page) {
        Integer pageNo = page.getPageNo();
        Integer pageSize = page.getPageSize();
        if (pageNo == null || pageNo <= 0 || pageSize == null || pageSize <= 0) {
            throw new CustomException(ResultStatus.ERROR.getStatusCode(), ResultStatus.ERROR.getStatusMessage());
        }
        PageHelper.startPage(pageNo, pageSize);
        Scenic data = page.getData();
        List<Scenic> scenicList = scenicDao.queryAll(data);
        return new PageInfo(scenicList);
    }

    @Override
    public int add(Scenic scenic) {
        // 1. 先插入景区数据，此时会触发主键回填
        int insertCount = scenicDao.add(scenic);
        // 检查插入是否成功
        if (insertCount>0) {
            // 2. 此时 scenicId 已被数据库自动生成并回填
            Integer scenicId = scenic.getScenicId();
            System.out.println("刚插入的scenicId：" + scenicId);
            if (scenicId != null) {
                // 3. 插入审核记录
                ScenicAudit scenicAudit = new ScenicAudit();
                scenicAudit.setScenicId(scenicId);
                scenicAudit.setAuditStatus("0"); // 0表示待审核
                //插入默认delFlag=0
                scenicAudit.setDelFlag("0");
                // 调用审计DAO插入
                scenicAuditDao.insert(scenicAudit);// 需要实现该方法
            }
        }
        return insertCount;
    }

    @Override
    public int update(Scenic scenic) {

        // 2. 查询是否存在审核记录
        ScenicAudit scenicAudit = scenicAuditDao.queryByScenicId(scenic.getScenicId());

        if (scenicAudit != null) {
            // 若存在，更新审核状态
            scenicAudit.setAuditStatus("0");
            scenicAudit.setRejectReason("");
            scenicAudit.setDelFlag("0");
            scenicAudit.setAuditPeople("");
            //设置审核时间为空
            scenicAudit.setAuditTime(null);
            scenicAuditDao.update(scenicAudit);
        }
        return scenicDao.update(scenic);
    }

    @Override
    public int deleteById(Integer scenicId) {
        //设置审核状态为景区已删除3
        ScenicAudit scenicAudit = new ScenicAudit();
        scenicAudit.setScenicId(scenicId);
        scenicAudit.setAuditStatus("3");
        scenicAuditDao.updateByScenicId(scenicAudit);
        return scenicDao.deleteById(scenicId);
    }


    /**
     * 上传景区图片
     * @param file 上传的文件
     * @return 上传结果和文件路径
     */
    @Override
    public Result uploadImage(MultipartFile file) {
        if (file.isEmpty()) {
            return ResultUtil.error("上传文件为空");
        }

        // 检查文件类型
        String contentType = file.getContentType();
        if (!"image/jpeg".equals(contentType) && !"image/png".equals(contentType)) {
            return ResultUtil.error("只允许上传JPG/PNG格式的图片");
        }

        // 检查文件大小（最大10MB）
        long size = file.getSize();
        if (size > 10 * 1024 * 1024) {
            return ResultUtil.error("图片大小不能超过10MB");
        }

        try {
            // 获取项目根目录下的resources/static/img/scenic目录 (源代码目录)
            String srcPath = System.getProperty("user.dir") + "/src/main/resources/static/img/scenic/";
            File srcDir = new File(srcPath);
            if (!srcDir.exists()) {
                srcDir.mkdirs();
            }

            // 获取target/classes/static/img/scenic目录 (编译后目录)
            String targetPath = System.getProperty("user.dir") + "/target/classes/static/img/scenic/";
            File targetDir = new File(targetPath);
            if (!targetDir.exists()) {
                targetDir.mkdirs();
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename != null ?
                    originalFilename.substring(originalFilename.lastIndexOf(".")) : ".jpg";
            String newFilename = UUID.randomUUID().toString().replace("-", "") + fileExtension;

            // 保存文件到源代码目录
            String srcFilePath = srcPath + newFilename;
            file.transferTo(new File(srcFilePath));

            // 复制文件到target目录
            Files.copy(
                    new File(srcFilePath).toPath(),
                    new File(targetPath + newFilename).toPath(),
                    StandardCopyOption.REPLACE_EXISTING
            );

            // 返回可访问的URL路径
            String urlPath = "/img/scenic/" + newFilename;
            Map<String, String> data = new HashMap<>();
            data.put("url", urlPath);

            return ResultUtil.success(data);
        } catch (IOException e) {
            e.printStackTrace();
            return ResultUtil.error("文件上传失败: " + e.getMessage());
        }
    }
}